<template>
  <view class="settle-container">
    <view class="settle-header">
      <view class="settle-title">房间结算</view>
      <view class="room-info">房间号：{{roomId}}</view>
    </view>
    
    <!-- 成员积分列表 -->
    <view class="members-list">
      <view class="list-header">
        <text class="list-title">成员积分</text>
        <text class="collapse-all" @click="toggleAllDetails">
          {{isAllExpanded ? '全部收起' : '全部展开'}}
        </text>
      </view>
      <view v-for="member in sortedMembers" 
            :key="member.openId" 
            class="member-card">
        <view class="member-header" @click="toggleDetail(member.openId)">
          <view class="member-basic">
            <image class="member-avatar" :src="member.avatarUrl" mode="aspectFill"></image>
            <view class="member-info">
              <text class="member-name">{{member.nickname}}</text>
              <text class="member-score" :class="{'score-positive': member.score > 0, 'score-negative': member.score < 0}">
                {{member.score > 0 ? '+' : ''}}{{member.score}}
              </text>
            </view>
          </view>
          <view class="toggle-icon" :class="{'expanded': expandedMembers.includes(member.openId)}">
            <text class="arrow">›</text>
          </view>
        </view>
        
        <!-- 支付详情 -->
        <view class="payment-details" 
              v-if="expandedMembers.includes(member.openId)" 
              :class="{'positive': member.score > 0}">
          <view class="details-title">
            {{member.score < 0 ? '需支付给：' : '可收款：'}}
          </view>
          <view v-for="payment in getPaymentDetails(member)" 
                :key="payment.to" 
                class="payment-item">
            <text class="payment-user">{{payment.nickname}}</text>
            <text class="payment-amount">{{payment.amount}}</text>
          </view>
          <view class="total-payment">
            <text>{{member.score < 0 ? '总支付' : '总收款'}}：</text>
            <text class="total-amount">{{Math.abs(member.score)}}</text>
          </view>
        </view>
      </view>
    </view>
    
    <button class="back-btn" @click="goToProfile">返回首页</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      roomId: '',
      members: [],
      expandedMembers: [], // 记录展开状态的成员ID
      isAllExpanded: true, // 是否全部展开
    }
  },
  computed: {
    sortedMembers() {
      // 按积分降序排序，负分在前
      return [...this.members].sort((a, b) => {
        if (a.score < 0 && b.score >= 0) return -1;
        if (a.score >= 0 && b.score < 0) return 1;
        return b.score - a.score;
      });
    }
  },
  onLoad(options) {
    if (options.roomId) {
      this.roomId = options.roomId;
      this.loadSettleData();
    }
  },
  methods: {
    async loadSettleData() {
      try {
        const result = await uniCloud.callFunction({
          name: 'room',
          data: {
            action: 'getSettleData',
            data: {
              roomId: this.roomId
            }
          }
        });
        
        if (result.result.code === 0) {
          this.members = result.result.data.members;
          // 初始化展开状态
          this.expandedMembers = this.members.map(m => m.openId);
          this.isAllExpanded = true;
        } else {
          throw new Error(result.result.msg);
        }
      } catch (e) {
        console.error('加载结算数据失败:', e);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    },
    toggleDetail(memberId) {
      const index = this.expandedMembers.indexOf(memberId);
      if (index === -1) {
        this.expandedMembers.push(memberId);
        if (this.expandedMembers.length === this.members.length) {
          this.isAllExpanded = true;
        }
      } else {
        this.expandedMembers.splice(index, 1);
        this.isAllExpanded = false;
      }
    },
    toggleAllDetails() {
      if (this.isAllExpanded) {
        this.expandedMembers = [];
      } else {
        this.expandedMembers = this.members.map(m => m.openId);
      }
      this.isAllExpanded = !this.isAllExpanded;
    },
    getPaymentDetails(member) {
      const payments = [];
      const amount = Math.abs(member.score);
      
      if (member.score < 0) {
        // 负分成员需要支付的明细
        let remainingAmount = amount;
        this.members.forEach(m => {
          if (m.score > 0 && remainingAmount > 0) {
            const payAmount = Math.min(m.score, remainingAmount);
            payments.push({
              to: m.openId,
              nickname: m.nickname,
              amount: payAmount
            });
            remainingAmount -= payAmount;
          }
        });
      } else if (member.score > 0) {
        // 正分成员可以收到的明细
        let remainingAmount = amount;
        this.members.forEach(m => {
          if (m.score < 0 && remainingAmount > 0) {
            const receiveAmount = Math.min(Math.abs(m.score), remainingAmount);
            payments.push({
              to: m.openId,
              nickname: m.nickname,
              amount: receiveAmount
            });
            remainingAmount -= receiveAmount;
          }
        });
      }
      
      return payments;
    },
    goToProfile() {
      uni.switchTab({
        url: '/pages/profile/profile'
      });
    }
  }
}
</script>

<style>
.settle-container {
  min-height: 100vh;
  padding: 30rpx;
  background-color: #f5f5f5;
}

.settle-header {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.settle-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.room-info {
  font-size: 28rpx;
  color: #666;
}

.members-list {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.collapse-all {
  font-size: 26rpx;
  color: #409EFF;
  padding: 10rpx;
}

.member-card {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.member-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  cursor: pointer;
}

.member-basic {
  display: flex;
  align-items: center;
  flex: 1;
}

.member-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.member-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.member-name {
  font-size: 28rpx;
  color: #333;
}

.member-score {
  font-size: 32rpx;
  font-weight: 500;
}

.score-positive {
  color: #52c41a;
}

.score-negative {
  color: #ff4d4f;
}

.toggle-icon {
  padding: 0 20rpx;
  transition: transform 0.3s ease;
}

.toggle-icon .arrow {
  display: inline-block;
  font-size: 32rpx;
  color: #999;
  transform: rotate(90deg);
}

.toggle-icon.expanded .arrow {
  transform: rotate(-90deg);
}

.payment-details {
  padding: 20rpx;
  background-color: #f9f9f9;
  border-top: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.payment-details.positive {
  background-color: #f6ffed;
  border-top: 1rpx solid #b7eb8f;
}

.details-title {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
}

.payment-user {
  font-size: 28rpx;
  color: #409EFF;
}

.payment-amount {
  font-size: 28rpx;
  color: #ff4d4f;
}

.total-payment {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  margin-top: 10rpx;
  border-top: 1rpx dashed #eee;
  font-size: 28rpx;
  color: #666;
}

.total-amount {
  font-weight: bold;
  color: #ff4d4f;
}

.back-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #07c160;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 40rpx;
}
</style> 